package com.tanhua.mogon.api;

import com.tanhua.api.UserLocationApi;
import com.tanhua.model.mongo.UserLocation;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@DubboService
public class UserLocationApiImpl implements UserLocationApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     *上报地理位置
     * @param userId
     * @param longitude
     * @param latitude
     * @param addrStr
     * @return
     */
    @Override
    public Boolean updateLocation(Long userId, Double longitude, Double latitude, String addrStr) {
        try {
            //1、根据用户id查询位置信息
            //构建查询条件
            Query query = Query.query(Criteria.where("userId").is(userId));
            //查询
            UserLocation userLocation = mongoTemplate.findOne(query,UserLocation.class);
            //2.判断该用户是否存在位置信息
            if (userLocation == null){
                //不存在，保存地理位置
                //创建地理位置对象
                userLocation = new UserLocation();
                //封装数据
                userLocation.setUserId(userId);
                userLocation.setAddress(addrStr);
                userLocation.setCreated(System.currentTimeMillis());
                userLocation.setUpdated(System.currentTimeMillis());
                userLocation.setLastUpdated(System.currentTimeMillis());
                userLocation.setLocation(new GeoJsonPoint(longitude, latitude));
                //保存到数据库表中
                mongoTemplate.save(userLocation);
            }else {
                //存在，则更新地理位置
                Update update = Update.update("location", new GeoJsonPoint(longitude, latitude))
                        .set("updated", System.currentTimeMillis())
                        .set("lastUpdated",System.currentTimeMillis())
                        .set("address",addrStr);
                //修改数据库中的数据
                mongoTemplate.updateFirst(query, update, UserLocation.class);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 搜索附近的人
     * @param userId
     * @param distance
     * @return
     */
    @Override
    public List<Long> queryNearUser(Long userId, String distance) {
        //1.构建查询条件，根据用户id查询用户位置的信息
        Query query = Query.query(Criteria.where("userId").is(userId));
        UserLocation userLocation = mongoTemplate.findOne(query, UserLocation.class);
        //2.判断该用户是否存在地理位置
        if (userLocation == null){
            //不存在
            return new ArrayList<>();
        }
        //构造坐标点(该坐标点应该是当前用户的地理位置点，则通过该用户id进行查询)
        GeoJsonPoint point = userLocation.getLocation();
        //构造半径
        Distance distanceObj = new Distance(Double.valueOf(distance)/1000 , Metrics.KILOMETERS);
        //画了一个圆圈
        Circle circle = new Circle(point, distanceObj);
        //构造query对象
        Query query1 = Query.query(Criteria.where("location").withinSphere(circle));
        //省略其他内容
        List<UserLocation> list = mongoTemplate.find(query1, UserLocation.class);
//        list.forEach(System.out::println);
        //返回查询的用户的ids
        return list.stream().map(UserLocation::getUserId).collect(Collectors.toList());
    }
}
